// yunlianfangzhou-detector.js - 云链方舟插件检测器
(function() {
    'use strict';
    
    // 全局变量
    let extensionId = null;
    let isDetected = false;
    
    // 获取浏览器扩展API
    function getExtensionAPI() {
        if (typeof chrome !== 'undefined' && chrome.runtime) {
            return chrome;
        }
        return null;
    }
    
    const extensionAPI = getExtensionAPI();
    
    // 检测器类
    class YunLianFangZhouDetector {
        constructor() {
            this.extensionId = null;
            this.isDetected = false;
            this.version = '1.0.0';
            this.pluginName = '云链方舟插件';
        }
        
        // 检测插件是否安装
        async detect() {
                return new Promise((resolve) => {
                try {
                    console.log('开始检测插件...');
                    
                    // 检查chrome API是否可用
                    if (typeof chrome === 'undefined' || !chrome.runtime) {
                        console.error('Chrome扩展API不可用，请确保在支持扩展的浏览器中运行');
                        this.isDetected = false;
                        resolve(false);
                        return;
                    }
                    
                    console.log('Chrome扩展API可用');
                    
                    // 创建检测元素
                    const detectionElement = document.createElement('div');
                    detectionElement.id = 'yunlianfangzhou-detection';
                    detectionElement.setAttribute('data-plugin-name', '云链方舟插件');
                    detectionElement.setAttribute('data-request-extension-id', 'true');
                    detectionElement.style.display = 'none';
                    
                    document.documentElement.appendChild(detectionElement);
                    console.log('检测元素已注入');
                    
                    // 等待插件响应（增加等待时间）
                    setTimeout(() => {
                        if (detectionElement.getAttribute('data-detected') === 'true') {
                            this.isDetected = true;
                            this.extensionId = detectionElement.getAttribute('data-extension-id');
                            console.log('插件检测成功:', {
                                version: detectionElement.getAttribute('data-version'),
                                extensionId: this.extensionId
                            });
                        } else {
                            this.isDetected = false;
                            console.error('插件检测失败，可能的原因：');
                            console.error('1. 插件未安装或未启用');
                            console.error('2. Content Script未正确注入');
                            console.error('3. 插件权限配置问题');
                            console.error('请检查 edge://extensions/ 中的插件状态');
                        }
                        
                        // 清理检测元素
                        document.documentElement.removeChild(detectionElement);
                        resolve(this.isDetected);
                    }, 2000); // 增加等待时间到2秒
                    
                } catch (error) {
                    console.error('插件检测出错:', error);
                    this.isDetected = false;
                    resolve(false);
                }
            });
        }
        
        // 检测插件并获取扩展ID
        async detectWithExtensionId() {
            const detected = await this.detect();
            return {
                detected: detected,
                extensionId: this.extensionId,
                version: this.version,
                pluginName: this.pluginName
            };
        }
        
        // 清除cookies并开始监听
        async clearAndWaitForCookies(loginUrl, cookieDomain) {
            if (!this.isDetected || !this.extensionId) {
                throw new Error('插件未检测到或扩展ID不可用');
            }
            
            return new Promise((resolve, reject) => {
                const message = {
                    action: 'clearAndWaitForCookies',
                    loginUrl: loginUrl,
                    cookieDomain: cookieDomain
                };
                
                extensionAPI.runtime.sendMessage(this.extensionId, message, (response) => {
                    if (extensionAPI.runtime.lastError) {
                        reject(new Error(extensionAPI.runtime.lastError.message));
                        } else if (response && response.success) {
                        resolve(response);
                        } else {
                        reject(new Error(response ? response.error : '插件响应失败'));
                    }
                });
            });
        }
        
        // 获取存储的cookies
        async getStoredCookies() {
            if (!this.isDetected || !this.extensionId) {
                throw new Error('插件未检测到或扩展ID不可用');
            }
            
            return new Promise((resolve, reject) => {
                const message = {
                    action: 'getStoredCookies'
                };
                
                extensionAPI.runtime.sendMessage(this.extensionId, message, (response) => {
                    if (extensionAPI.runtime.lastError) {
                        reject(new Error(extensionAPI.runtime.lastError.message));
                    } else {
                        resolve(response || { success: false, message: '无响应' });
                    }
                });
            });
        }
        
        // 停止cookie监听
        async stopCookieMonitoring() {
            if (!this.isDetected || !this.extensionId) {
                throw new Error('插件未检测到或扩展ID不可用');
            }
            
            return new Promise((resolve, reject) => {
                const message = {
                    action: 'stopCookieMonitoring'
                };
                
                extensionAPI.runtime.sendMessage(this.extensionId, message, (response) => {
                    if (extensionAPI.runtime.lastError) {
                        reject(new Error(extensionAPI.runtime.lastError.message));
                    } else {
                        resolve(response || { success: false, message: '无响应' });
                    }
                });
            });
        }
        
        // 完整的添加店铺流程
        async addShop(shopType, platformConfig, addShopFn) {
            try {
                // 1. 检测插件
                if (!this.isDetected) {
                    await this.detect();
                }
                
                if (!this.isDetected) {
                    throw new Error('插件未安装');
                }
                
                // 2. 清除cookies并开始监听
                await this.clearAndWaitForCookies(platformConfig.loginUrl, platformConfig.cookieDomain);
                
                // 3. 轮询获取cookies
                const cookies = await this.pollForCookies();
                
                // 4. 调用外部API函数
                const result = await addShopFn(shopType, cookies);
                
                return result;
                
            } catch (error) {
                throw new Error(`添加店铺失败: ${error.message}`);
            }
        }
        
        // 轮询获取cookies
        async pollForCookies() {
            const maxAttempts = 300; // 5分钟
            let attempts = 0;
            
            return new Promise((resolve, reject) => {
                const pollInterval = setInterval(async () => {
                    attempts++;
                    
                    try {
                        const response = await this.getStoredCookies();
                        
                        if (response.success && response.cookies) {
                            clearInterval(pollInterval);
                            resolve(response.cookies);
                        } else if (attempts >= maxAttempts) {
                            clearInterval(pollInterval);
                            reject(new Error('获取cookies超时'));
                        }
                    } catch (error) {
                        clearInterval(pollInterval);
                        reject(error);
                    }
                }, 1000);
            });
        }
        
        // 使用预定义配置添加店铺
        async addShopByType(shopType, addShopFn) {
            const platformConfigs = {
                1: {
                    name: '美团',
                    loginUrl: 'https://e.waimai.meituan.com/login',
                    cookieDomain: 'e.waimai.meituan.com'
                },
                2: {
                    name: '饿了么',
                    loginUrl: 'https://melody.shop.ele.me/app/shop/1293360190/dashboard#app.shop.dashboard',
                    cookieDomain: 'melody.shop.ele.me'
                },
                3: {
                    name: '京东到家',
                    loginUrl: 'https://store.jddj.com/login',
                    cookieDomain: 'store.jddj.com'
                }
            };
            
            const config = platformConfigs[shopType];
            if (!config) {
                throw new Error(`不支持的平台类型: ${shopType}`);
            }
            
            return await this.addShop(shopType, config, addShopFn);
        }
        
        // 监听插件检测事件
        onDetected(callback) {
            document.addEventListener('yunlianfangzhou-detected', callback);
        }
        
        // 移除检测事件监听器
        removeDetectedListener(callback) {
            document.removeEventListener('yunlianfangzhou-detected', callback);
        }
        
        // 获取所有平台配置
        getPlatformConfigs() {
            return {
                1: { name: '美团', loginUrl: 'https://e.waimai.meituan.com/login', cookieDomain: 'e.waimai.meituan.com' },
                2: { name: '饿了么', loginUrl: 'https://melody.shop.ele.me/app/shop/1293360190/dashboard#app.shop.dashboard', cookieDomain: 'melody.shop.ele.me' },
                3: { name: '京东到家', loginUrl: 'https://store.jddj.com/login', cookieDomain: 'store.jddj.com' }
            };
        }
        
        // 获取指定平台配置
        getPlatformConfig(shopType) {
            const configs = this.getPlatformConfigs();
            return configs[shopType] || null;
        }
    }
    
    // 创建全局实例
    const detector = new YunLianFangZhouDetector();
    
    // 暴露到全局
    window.YunLianFangZhou = detector;
    
    // 自动检测插件
    detector.detect().then((detected) => {
        if (detected) {
            console.log('云链方舟插件已检测到');
            // 触发检测事件
        const event = new CustomEvent('yunlianfangzhou-detected', {
                detail: {
                    detected: true,
                    extensionId: detector.extensionId,
                    version: detector.version,
                    pluginName: detector.pluginName
                }
        });
        document.dispatchEvent(event);
        } else {
            console.log('云链方舟插件未检测到');
        }
    });
    
    console.log('云链方舟插件检测器已加载');
})();